//
//  WmcTeamCloudAlbumMembers.swift
//  YPWatermarkCamera
//
//  Created by 赵洋 on 2022/9/8.
//

import MJRefresh
import UIKit

// MARK: - 扩展WmcTeamCloudAlbumMembersVC + WmcVMProtocol

extension WmcTeamCloudAlbumMembersVC: WmcVMProtocol {
    typealias VMType = WmcTeamCloudAlbumMembersVM
}

// MARK: - [WmcTeamCloudAlbumMembersVC]

class WmcTeamCloudAlbumMembersVC: WmcBaseVC, WmcStatefulViewController {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupInitialViewState()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        getData()
        setupPlaceholders()
        
        /// 添加成员成功，通知回调刷新当前页面
        WmcNotificationManager.shared.addObserver(type: .addTeamMemberSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .editTeamRemarkSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .editTeamNameSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .editUserAvatarSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .deleteTeamMemberSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
            WmcHudManager.toast("删除成功")
        }

        WmcNotificationManager.shared.addObserver(type: .editUserNameSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
        
        WmcNotificationManager.shared.addObserver(type: .deletePhotoSucceed) {[weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
    }

    /// 设置占位视图
    /// - Returns: description
    func setupPlaceholders() {
        loadingView = WmcLoadingView()
        emptyView = WmcTeamMemberEmptyListView.emptyView(img: "team_member_list_empty", note: "未找到相关成员")
        let errView = WmcErrorView()
        errView.refreshClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
        errorView = errView
    }

    func getData() -> Void {
        if lastState == .loading {
            return
        }
        startLoading()
        viewModel.getTeamMemberList()
    }
    
    override func makeUI() {
        makeNavView(style: .white, showShadow: false)
        addNaviLineView()

        view.backgroundColor = UIColor.wmc_gray_F7F8FA

        title = viewModel.title

        view.addSubview(searchView)
        view.addSubview(headerView)
        view.addSubview(tableView)

        searchView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
        }

        headerView.snp.makeConstraints { make in
            make.top.equalTo(searchView.snp.bottom)
            make.left.right.equalToSuperview()
        }

        tableView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(8)
            make.left.right.bottom.equalToSuperview()
        }
    }

    override func bindViewModel() {
        viewModel.members.skip(1).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
            weakSelf.endLoading(animated: true, error: nil, completion: nil)
            print("fuck state === \(weakSelf.currentState)")
        }.disposed(by: rx.disposeBag)

        viewModel.error.bind { [weak self] error in
            guard let weakSelf = self,let error = error else { return }
            weakSelf.endLoading(animated: true, error: error, completion: nil)
        }.disposed(by: rx.disposeBag)
    }

    override func bindViewAction() {
        headerView.rx.tapGesture().skip(1).bind { [weak self] _ in
            guard let weakSelf = self, let team = weakSelf.viewModel.teamAblum, let member = weakSelf.viewModel.mySelf else { return }
            let vm = WmcTeamCloudInviteMemberVM()
            vm.teamAblum = team
            vm.teamMember = member
            // 标记当前跳转，以便后续回到次位置
            weakSelf.popToVCMark = true
            WmcNavigatorManager.push(.inviewTeamMember, parms: vm)?.hidesBottomBarWhenPushed = true
        }.disposed(by: rx.disposeBag)

        searchView.inputTextfield.rx.text.skip(1).bind(onNext: viewModel.searchMembers(searchStr:)).disposed(by: rx.disposeBag)
    }

    lazy var searchView: WmcTeamMemberSearchView = {
        let view = WmcTeamMemberSearchView()
        view.placeholder = "请输入姓名"
        return view
    }()

    lazy var headerView: WmcTeamMemberHeaderView = {
        let view = WmcTeamMemberHeaderView()
        return view
    }()

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect.zero, style: .plain)
        view.delegate = self
        view.dataSource = self
        view.register(WmcTeamCloudMemberCell.self, forCellReuseIdentifier: "WmcTeamCloudMemberCell")
        view.separatorStyle = .none
        view.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.getData()
            weakSelf.tableView.mj_header?.endRefreshing()
        })
        view.backgroundColor = UIColor.wmc_gray_F7F8FA
        return view
    }()

    lazy var currentEmptyView: WmcTeamMemberEmptyListView = {
        let view = WmcTeamMemberEmptyListView.emptyView(img: "team_member_list_empty", note: "未找到相关成员")
        return view
    }()
}

extension WmcTeamCloudAlbumMembersVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in _: UITableView) -> Int {
        return 1
    }

    func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
        return viewModel.members.value.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "WmcTeamCloudMemberCell", for: indexPath) as! WmcTeamCloudMemberCell
        let model = viewModel.members.value[indexPath.row]
        cell.configure(model: model)
        return cell
    }

    func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = viewModel.members.value.yp.object(at: indexPath.row)
        let vm = WmcTeamCloudMemberDetailVM()
        vm.teamMember = model
        vm.teamAblum = viewModel.teamAblum
        WmcNavigatorManager.push(.teamCloudMemberDetail, parms: vm)?.hidesBottomBarWhenPushed = true
    }
}

extension WmcTeamCloudAlbumMembersVC {
    func hasContent() -> Bool {
        return viewModel.members.value.count > 0
    }

    func handleErrorWhenContentAvailable(_ error: Error) {
        /// 处理错误
        print(error)
    }
}
